<template>
  <div class="navigator">
    <div class="caret-box" @click="handleLeft">
      <i class="fa fa-caret-left" :class="{disabledLeft: artInfo.index === latestIndex}"></i>
    </div>
    <span class="title">{{ artInfo.title }}</span>
    <div class="caret-box caret-box-right" @click="handleRight">
      <i class="fa fa-caret-right" :class="{disabledRight: artInfo.index === 1}"></i>
    </div>
  </div>
</template>

<script>
import request from '../../utils/request'
export default {
  data() {
    return {
      latestIndex: null,
    }
  },
  props: ['artInfo'],
  created() {
    const latestIndex = wx.getStorageSync('latestIndex')
    this.latestIndex = latestIndex
  },
  methods: {
    getKey(index) {
      // 生成缓存的key
      return `jiudao_${index}`
    },
    getStorageInfo(key, eventName) {
      const getStorageInfo = wx.getStorageSync(key)
      this.$emit(eventName, getStorageInfo)
    },
    requestClassicInfo(url, eventName) {
      request({
        url
      }).then((result) => {
        wx.setStorageSync(this.getKey(result.index), result);
        this.$emit(eventName, result)
      })
    },
    handleLeft() {
      // 获取当前一期的下一期
      const { index } = this.artInfo
      if (index < this.latestIndex) {
        const storageInfo = wx.getStorageSync(this.getKey(index + 1))
        if (storageInfo) {
          // 缓存取数据
          this.getStorageInfo(this.getKey(index + 1), 'update-left')
        } else {
          // API取数据
          this.requestClassicInfo(`classic/${index}/next`, 'update-left')
        }
      }
    },
    handleRight() {
      // 获取当前一期的上一期
      const { index } = this.artInfo
      if (index > 1) {
        const storageInfo = wx.getStorageSync(this.getKey(index - 1))
        if (storageInfo) {
          // 缓存取数据
          this.getStorageInfo(this.getKey(index - 1), 'update-right')
        } else {
          // API取数据
          this.requestClassicInfo(`classic/${index}/previous`, 'update-right')
        }
      }
    }
  }
};
</script>

<style scoped>
.navigator {
  margin: 0 auto 100rpx;
  width: 600rpx;
  height: 80rpx;
  background-color: #f7f7f7;
  border-radius: 2px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20rpx;
}
.caret-box {
  width: 50rpx;
  height: 50rpx;
}
.caret-box-right {
  text-align: right;
}
.fa-caret-left,
.fa-caret-right {
  font-size: 52rpx;
}
.disabledLeft,
.disabledRight {
  color: #bbb;
}
.title {
  font-size: 28rpx;
}
</style>